package com.xiaoyun.service.strategy.manage;

import com.xiaoyun.enums.OperatorFriendRequestTypeEnum;
import com.xiaoyun.service.strategy.IOperatorFriendStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class IOperFriendManage implements BeanPostProcessor {

    private static final Map<OperatorFriendRequestTypeEnum, IOperatorFriendStrategy>
            typeIndex = new HashMap<>(OperatorFriendRequestTypeEnum.values().length);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof IOperatorFriendStrategy)) {
            return bean;
        }
        IOperatorFriendStrategy iOperatorFriendStrategy = (IOperatorFriendStrategy) bean;
        OperatorFriendRequestTypeEnum type = iOperatorFriendStrategy.type();
        if (typeIndex.containsKey(type)) {
            throw new IllegalStateException("重复注册");
        }
        typeIndex.put(type, iOperatorFriendStrategy);

        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof IOperatorFriendStrategy)) {
            return bean;
        }
        return null;
    }

    public void exec(Integer typeEnum, String sendUserId, String acceptUserId) {
        typeIndex.get(OperatorFriendRequestTypeEnum.getMsgByEnum(typeEnum)).execution(sendUserId, acceptUserId);
    }
}
